/*
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-01-05 14:46:49
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-22 16:48:43
 */
import { defineStore } from '@/common/config/defineStore'
import { apiGetFindDictItem } from '../api/dictValue'
import { apiPostAreaTree } from '../../resourceAdmin/api/area'
// import { defineStore } from 'pinia'
// 第一个参数是应用程序中 store 的唯一 id
export default defineStore('dictValue', {
  state: () => ({
    dictItemOptions: {
      name: '000000'
    },
    addressOptions: [] // 此处数据仅到省市区
  }),
  // 相当于 vue 中的 computed 计算属性 返回一个数值
  getters: {
    // getDictItem: (state, key) => {
    //   return state.dictItemOptions[key] || null
    // }
  },
  actions: {
    getDictItem(key) {
      return this.dictItemOptions[key] || null
    },
    // getDictItem(dictKey) {
    //   return new Promise((resolve, reject) => {
    //     ;async () => {
    //       const value = this.dictItemOptions[dictKey] || null
    //       resolve(value)
    //     }
    //   })
    // },
    // 单独设置字典缓存值
    setDictItem(dictKey, dictArr) {
      this.dictItemOptions[dictKey] = dictArr
    },
    getAddressOptions() {
      apiPostAreaTree({ beginLevel: 1, endLevel: 3 }).then(({ data }) => {
        this.addressOptions = data
      })
    },
    getSelectionDict(dictKey) {
      return new Promise((resolve, reject) => {
        ;(async () => {
          try {
            if (!this.dictItemOptions[dictKey]) {
              const { data } = await apiGetFindDictItem(dictKey)
              this.dictItemOptions[dictKey] = data
            }
            resolve(this.dictItemOptions[dictKey])
          } catch (error) {
            reject(error)
          }
        })()
      })
    }
  }
})
